<template>
  <div class="user-edit">
    <div class="user-img">
      <span>头像</span>
      <div v-if="isEmpty(userInfos.profilePicture)">
        <img src="../assets/img/null.jpg" alt="" ref="userIcon">
      </div>
      <div v-else>
        <img :src="userInfos.profilePicture" ref="userIcon">
      </div>
      <input type="file" multiple accept="image/*" id="chat_file" @change="uploadAvatar">
    </div>
    <div class="user-nick">
      <i>昵称</i>
      <span contenteditable="true" ref="nick"></span>
    </div>
    <van-button type="primary" class="saveuser" @click="save">保存</van-button>
  </div>
</template>

<script>
  import {mapState} from "vuex";
  import {user_data, user_setting, uploadImg} from "../api";
  import {mix} from '../mixins'

  export default {
    name: "editUserInfo",
    mixins: [mix],
    data() {
      return {
        userInfos: {},
        // userImg: ''
      }
    },
    mounted() {
      if (this.$store.getters.userInfo.name) {
        this.userInfos = this.$store.getters.userInfo
        this.$refs.nick.innerHTML = this.userInfos.name
      } else {
        user_data().then((res) => {
          console.log(res)
          this.userInfos = res.data.data
          this.$refs.nick.innerHTML = this.userInfos.name
          this.$store.commit('handleUserInfo', this.userInfos)
        })
      }
    },
    methods: {
      //图片上传
      uploadAvatar(input) {
        let file = input.target.files[0]
        if (!file) {
          return
        }
        if (typeof FileReader === 'undefined') {
          window.alert('浏览器版本过低!')
          return
        } else if (!/image\/\w+/.test(file.type)) {
          window.alert('必须上传图片')
          return
        }
        if (file.size <= 500 * 1024) {
          const reader1 = new FileReader()
          const _this = this
          reader1.onload = function () {
            const result = this.result
            _this.$refs.userIcon.src = result
            // _this.$store.commit('handleUserImg', result)
          }
          reader1.readAsDataURL(file)
          this.upload(file)
        } else {
          const reader = new FileReader()
          const _this = this
          reader.onload = function () {
            let result = this.result
            let img = new Image()
            img.src = result
            _this.$refs.userIcon.src = result
            // _this.$store.commit('handleUserImg', result)
            img.onload = function () {
              const file = _this.compress(img)
              const bytes = window.atob(file.split(',')[1])
              let array = []
              for (let i = 0; i < bytes.length; i++) {
                array.push(bytes.charCodeAt(i))
              }
              let blob = new Blob([new Uint8Array(array)], {
                type: 'image/jpeg'
              })
              _this.upload(blob)
            }
          }
          reader.readAsDataURL(file)
        }
      },

      // 上传图片
      upload(file) {
        this.isUpdating = true
        let data = new FormData()
        data.append('file', file, "myImg.jpeg")
        uploadImg(data).then((res) => {
          if (res.status === 200) {
            document.getElementById('chat_file').value = ''
            this.userInfos.profilePicture = res.data.msg
          }
          this.isUpdating = false
        })
      },

      // 压缩图片
      compress(img) {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d')
        // 图片原始尺寸
        let originWidth = img.width
        let originHeight = img.height
        // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
        let maxWidth = 400,
          maxHeight = 400
        // 目标尺寸
        let targetWidth = originWidth,
          targetHeight = originHeight
        // 图片尺寸超过300x300的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth
            targetHeight = Math.round(maxWidth * (originHeight / originWidth))
          } else {
            targetHeight = maxHeight
            targetWidth = Math.round(maxHeight * (originWidth / originHeight))
          }
        }
        // canvas对图片进行缩放
        canvas.width = targetWidth
        canvas.height = targetHeight
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight)
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight)
        let newUrl = canvas.toDataURL('image/jpeg', 0.5) //base64 格式
        return newUrl
      },

      save() {
        this.userInfos.name = this.$refs.nick.innerHTML
        if (this.isEmpty(this.userInfos.name)) {
          alert('请填写昵称')
          return
        }
        if (this.isUpdating) {
          alert('图片上传中,请稍等 ..')
          return
        }
        user_setting(JSON.stringify(this.userInfos)).then((res) => {
          // console.log(res)
          if (res.data.code == 0) {
            this.$store.commit('handleNickName', this.$refs.nick.innerHTML)
            this.showTips()
            // this.ws.send(JSON.stringify({cmd: 38, cmdType: 1}))
            Event.$emit('ws_send', JSON.stringify({cmd: 38, cmdType: 1}))
            this.$router.push({path: '/home'})
          }
        })
      },
      showTips() {
        this.$notify({
          title: '成功',
          duration: 2000,
          message: `修改成功`,
          type: 'success'
        });
      },
      isEmpty(str) {
        return str === null || str === ''
      },
    },
    created() {
      // this.ws = new WebSocket(this.getWsUrl());
    },
    computed: {
      ...mapState({
        userInfo: state => state.userInfo
      }),
      userInfo: {
        get() {
          return this.$store.state.userInfo
        },
        set(val) {
          this.$store.state.userInfo = val
        }
      }
    },
    watch: {
      userInfo() {
        this.userInfos = this.$store.getters.userInfo
      }
    },
  }
</script>

<style scoped lang="less">
  .user-edit {
    width: 100%;
    height: 100vh;
    background-color: #e4e3e3;
    padding-top: 30px;

    .user-img {
      display: flex;
      position: relative;
      justify-content: space-between;
      height: 50px;
      border-bottom: 1px solid #b1b6bb;
      margin: 0 21px;

      span {
        font-size: 16px;
      }

      img {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        transform: translateY(-20px);
      }
    }

    .user-nick {
      display: flex;
      justify-content: space-between;
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #b1b6bb;
      margin: 0 21px;
      font-size: 16px;

      span {
        padding: 0 9px;
        outline: none;
        border: none;
      }
    }

    .saveuser {
      width: 50%;
      margin-top: 30px;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }

    #chat_file {
      opacity: 0;
      position: absolute;
      width: 21%;
      height: 63px;
      right: -5px;
      top: -21px;
    }
  }
</style>
